<?
/**
 * VoiceOne Settings/Extensions/edit
 *
 * Frontend to provide access to the extensions system in voiceone.
 * @package voiceone
 * @subpackage  settings_extensions
 * @todo Remove hardcoded italian message for confirmation box (AlertGood. AlertBad etc)
 */

  include ("../../../../../admin/config/cfg.php");
  global $cwlang;
  require_once("$absBasePath/lib/xajax/xajax.inc.php");

  //================ XAJAX ================
  function processFormData($formData){
    global $asterisk,$cwlang,$relBasePath;
    // Instantiate the xajaxResponse object
    $objResponse = new xajaxResponse();
    // Extract form params
    $directory=$formData["directory"];
    $id=$directory["id"];
    $name=$directory["name"];
    $description=$directory["description"];
    $imgErr="<img src=\"".$relBasePath."/public/img/shutdown.png\" alt=\"error\">";
		// Check Name ((not null)&&(unique))
    $nameErr=false;
    $tNameArr=array();
  	$res=$asterisk->getProvDirectory(0);
  	if(is_array($res)){
    	foreach($res as $d){
      	if($d["id"]==$id) continue;
        $dNameArr[]=trim($d["name"]);
      }
  	}
    if(trim($name)=="") {
      //name cannot be null
      $errOut[]= T_("Name cannot be null");
      $objResponse->addAssign("nameErr","innerHTML",$imgErr);
      $nameErr=true;
    }else if((is_array($dNameArr))&&(in_array($name,$dNameArr,true))){
      //name must be unique
      $errOut[]= T_("Name already exists. Please change it");
      $objResponse->addAssign("nameErr","innerHTML",$imgErr);
      $nameErr=true;
    }
    if($nameErr===false) $objResponse->addAssign("nameErr","innerHTML","");
    // Process Form
    if(isset($errOut)){
      $error="<div class=\"AlertBad\"><ul>";
      foreach($errOut as $err) $error.="<li>".$err."</li>";
      $error.="</ul></div>";
      $objResponse->addAssign("alert","innerHTML",$error);
      $objResponse->addAssign("loading","innerHTML","");
    }else{
      $objResponse->addAssign("loading","innerHTML","");
      $script="document.getElementById('mainform').submit(); ";
      $objResponse->addScript($script);
    }
    // Return the xajaxResponse object
    return $objResponse->getXML();
  }
  function getList($search){
    global $asterisk,$cwlang,$relBasePath,$cwUserId;
    DEFINE("CONTACTS_IN_LIST", 100);
    // Instantiate the xajaxResponse object
    $objResponse = new xajaxResponse();
    // Create contact list
  	$opt="";
    $ret=$asterisk->getContactList($cwUserId,"",$search,CONTACTS_IN_LIST,1);
    if(!is_array($ret)){
    	$opt.="<option value=\"0\" disabled=\"disabled\">".T_("[search didn't match any contacts]")."</option>";
      $toomuchAlert="&nbsp;";
    }else{
    	if(count($ret)>99) $toomuchAlert=T_("(*) First 100 search results");
      else $toomuchAlert="&nbsp;";
      foreach($ret as $v){
        $id=$v["id"];
        $id_user=$v["id_user"];
        if(strlen($v["name"])>25) $name=substr($v["name"],0,25)."..."; else $name=$v["name"];
        $phonenumber=$v["phonenumber"];
        $mobile=$v["mobile"];
        if((trim($phonenumber)=="")&&(trim($mobile)=="")) $disabled="disabled=\"disabled\""; else $disabled="";
        $opt.="<optgroup id=\"optg_".$id."\" label=\"".$name."\" $disabled >";
        if(trim($phonenumber)!="") $opt.="<option value=\"p_".$id."\">".$phonenumber."</option>";
        if(trim($mobile)!="") $opt.="<option value=\"m_".$id."\">".$mobile."</option>";
        $opt.="</optgroup>";
      }
    }
  	// Return the xajaxResponse object
    $opt="<select id=\"c_select\" size=\"10\" multiple=\"multiple\">".$opt."</select>";
    $objResponse->addAssign("c_list","innerHTML",$opt);
    $objResponse->addAssign("toomuch","innerHTML",$toomuchAlert);
    return $objResponse->getXML();
  }
  $xajax = new xajax();
  $xajax->registerFunction("processFormData");
  $xajax->registerFunction("getList");
  $xajax->processRequests();
  //================== POST ====================
  if(count($_POST)>0){
    $directory=$_POST["directory"];
    $entry=Array(
        "id" => $directory["id"],
        "name" => $directory["name"],
        "phonenumber_prefix" => $directory["phonenumber_prefix"],
    		"mobile_prefix" => $directory["mobile_prefix"],
        "description" => $directory["description"]
      );
    //add contacts to directory
    $contacts=array();
    if(is_array($_POST["contacts"])){
      foreach($_POST["contacts"] as $v) {
      	$vArr=split("_",$v);
        if(is_array($vArr)){
        	$c=array();
        	$c["key"]=$vArr[1];
          if($vArr[0]==p) $c["value"]=1;
          else if($vArr[0]==m) $c["value"]=2;
          else $c["value"]=0;
          $contacts[]=$c;
        }
      }
    }
    $entry["contacts"]=$contacts;
    //put template
    $ret=$asterisk->putProvDirectory($entry);
    if($ret>0) $alert="<div class=\"AlertGood\">".T_("Directory has been successfully edited")."</div>";
    else $alert="<div class=\"AlertBad\">".T_("Directory has NOT been edited")."</div>";
    //go to main page
    goToMainPage($alert,"../");
  }
  //================ PAGE LOGIC ================
  //Get the client informations
  if (isset($_GET["id"]) and $_GET["id"]!="") {
    $id=$_GET["id"];
    $ret=$asterisk->getProvDirectory($id);
    if ($err=$asterisk->getError()) die("Error: $err");
    $p=$ret[0];
    $name=$p["name"];
    $description=$p["description"];
    $phonenumber_prefix=$p["phonenumber_prefix"];
    $mobile_prefix=$p["mobile_prefix"];
    $contactsArr=$p["contacts"];
    //Title
    $title=sprintf(T_("Edit Directory \"%1\$s\""), $name );
  }else{
    $id=0;
    //Title
    $title=T_("New Directory");
  }
  //set directory's contacts
  $opt="";
  if(is_array($contactsArr)){
  	$c_num_value=count($contactsArr);
  	foreach($contactsArr as $c){
    	$id_contact=$c["key"];
      if((trim($id_contact)=="")||($id_contact==0)) continue;
    	$ret=$asterisk->getContact($id_contact,$cwUserId);
      if((is_array($ret))&&(is_array($ret[0]))){
      	$arr=$ret[0];
      	if($arr["order_field"]=="name"){
        	if(trim($arr["company"])!="") $c_name=$arr["name"]." ".$arr["surname"]." (".$arr["company"].")";
          else $c_name=$arr["name"]." ".$arr["surname"];
        }else if($arr["order_field"]=="company"){
        	if((trim($arr["surname"])!="")||(trim($arr["name"])!="")) $c_name=$arr["company"]." (".$arr["surname"]." ".$arr["name"].")";
          else $c_name=$arr["company"];
        }else{
        	if(trim($arr["company"])!="") $c_name=$arr["surname"]." ".$arr["name"]." (".$arr["company"].")";
          else $c_name=$arr["surname"]." ".$arr["name"];
        }
        if($c["value"]==1){
        	$c_name="[".$arr["phonenumber"]."] ".$c_name;
          if(strlen($c_name)>25) $c_name=substr($c_name,0,25)."...";
        	$opt.="<option value=\"p_".$arr["id"]."\">".$c_name."</option>";
        }else if($c["value"]==2){
        	$c_name="[".$arr["mobile"]."] ".$c_name;
        	if(strlen($c_name)>25) $c_name=substr($c_name,0,25)."...";
      		$opt.="<option value=\"m_".$arr["id"]."\">".$c_name."</option>";
        }
      }
    }
  }else $c_num_value=0;
  $c_num_visual="(".$c_num_value."/100)";
	//Init script
  $initScript="<script> xajax_getList(''); </script>";
  //================ MAIN CONTENTS ================
  ob_start();
  $xajax->printJavascript("../../../../../admin/lib/xajax/");
  echo $initScript;
  ?>
    <?$nav="directory";include("../../navigation.php");?>
    <div class="SectionHeader">
      <div id="loading" style="float: right;"></div>
      <h1><?=$title?></h1>
      <h3><a href="../" class="admin" ><?=T_("Return without save")?></a></h3>
    </div>
    <div id="alert"></div>
    <div id="basic_form">
      <form id="mainform" action="<?=$PHP_SELF?>" method="post">
        <!-- General Info -->
        <h2><?=T_("General Informations")?></h2>
        <p class="blockintro"><?=T_("Directory's general informations")?></p>
        <div class="block">
          <dl>
            <dt class="required"><label for="directory[name]"><?=T_("Name")?>:</label></dt>
            <dd><input type="text" size="25" id="directory[name]" name="directory[name]" value="<?=$name?>" /><span id="nameErr"></span></dd>
            <dt class="required"><label for="directory[description]"><?=T_("Description")?>:</label></dt>
            <dd><textarea id="directory[description]" name="directory[description]" cols="50" ><?=$description?></textarea></dd>
          </dl>
        </div>
        <!-- Prefix -->
        <h2><?=T_("Prefix")?></h2>
        <p class="blockintro"><?=T_("Optional string to prepend to contact's name on directory")?></p>
        <div class="block">
          <dl>
            <dt class="required"><label for="directory[phonenumber_prefix]"><?=T_("Fixed")?>:</label></dt>
            <dd><input type="text" size="25" id="directory[phonenumber_prefix]" name="directory[phonenumber_prefix]" value="<?=$phonenumber_prefix?>" /> <span class="help"><?=T_("Prepend to contact's name for fixed number")?></span></dd>
            <dt class="required"><label for="directory[mobile_prefix]"><?=T_("Mobile")?>:</label></dt>
            <dd><input type="text" size="25" id="directory[mobile_prefix]" name="directory[mobile_prefix]" value="<?=$mobile_prefix?>" /> <span class="help"><?=T_("Prepend to contact's name for mobile number")?></span></dd>
          </dl>
        </div>
        <!-- Entities -->
        <h2><?=T_("Contacts List")?></h2>
        <p class="blockintro"><?=T_("List of contacts telephone numbers")?></p>
        <div class="block">
        	<div style="width:100%; overflow:hidden;">
          	<!-- All Contact List -->
          	<div style="float:left;padding:10px 0 10px 30px;">
            	<div style="height:30px;">
              	<input type="text" style="vertical-align:middle;" id="search" name="search" size="23" value="" onkeyup="if(event.keyCode==13){document.getElementById('c_list').innerHTML='<select size=\'10\'></select><div style=\'display:inline;\'><img style=\'vertical-align:top;padding-left:5px;\' src=\'<?=$relBasePath?>public/img/ico-progress.gif\'/><span style=\'vertical-align:top;\'>&nbsp;<?=T_("loading...")?></span></div>';xajax_getList(document.getElementById('search').value);} return false;" />
              	<input type="image" style="vertical-align:top;cursor:pointer;" src="<?=$relBasePath?>/public/img/search.gif" alt="Search" onclick="document.getElementById('c_list').innerHTML='<select size=\'10\'></select><div style=\'display:inline;\'><img style=\'vertical-align:top;padding-left:5px;\' src=\'<?=$relBasePath?>public/img/ico-progress.gif\'/><span style=\'vertical-align:top;\'>&nbsp;<?=T_("loading...")?></span></div>';xajax_getList(document.getElementById('search').value);return false;"/>
              </div>
              <div id="toomuch" style="line-height:20px;color:#666;margin:0;padding:0;border:0;">&nbsp;</div>
              <div id="c_list">
            		<select size="10"></select>
              	<div style="display:inline;"><img style="vertical-align:top;" src="<?=$relBasePath?>public/img/ico-progress.gif"/><span style="vertical-align:top;">&nbsp;<?=T_("loading...")?></span></div>
              </div>
              <div style="text-align:center;padding-top:5px;">
              	<img style='vertical-align:top;' src='<?=$relBasePath?>public/img/unknown.gif'/>
              	<a href="" onclick="document.getElementById('search').value='';document.getElementById('c_list').innerHTML='<select size=\'10\'></select><div style=\'display:inline;\'><img style=\'vertical-align:top;padding-left:5px;\' src=\'<?=$relBasePath?>public/img/ico-progress.gif\'/><span style=\'vertical-align:top;\'>&nbsp;<?=T_("loading...")?></span></div>';xajax_getList('');return false;"><?=T_("reset search")?></a>
              </div>
            </div>
            <!-- Add Buttons -->
            <div style="float:left;padding:110px 30px 0 30px;width:80px;">
            	<input type="button" onclick="add()" value="<?=T_("&nbsp;&nbsp;&nbsp;Add&nbsp;&nbsp;&nbsp;>&nbsp;")?>"/>
            	<input type="button" onclick="addAll()" value="<?=T_("Add All >>")?>"/>
            </div>
            <!-- Group's Contact List -->
            <div style="float:left;padding-top:40px;">
            	<div id="c_num_visual" style="line-height:20px;color:#666;margin:0;padding:0;border:0;"><?=$c_num_visual?></div>
            	<select name="contacts[]" id="g_select" size="10" multiple="multiple"><?=$opt?></select>
              <div style="text-align:center;padding-top:5px;">
              	<img style='vertical-align:top;' src='<?=$relBasePath?>public/img/trash.gif'/>
                <a href="" onclick="remove();return false;"><?=T_("remove selected")?></a>
              </div>
            </div>
            <input id="c_num_value" type="hidden" value="<?=$c_num_value?>" />
          </div>
        </div>
        <!-- Buttons -->
        <div class="action">
          <?if ($_GET["id"]!="") {?> <input type="hidden" id="directory[id]" name="directory[id]" value="<?=$id?>" /><?}?>
          <a href="#"><img src="<?=$relBasePath?>/public/img/<?=$cwLanguage?>/b-cancel.gif" alt="Cancel" onclick="location.href='../'; return false;"/></a>
          <a href="#"><img src="<?=$relBasePath?>/public/img/<?=$cwLanguage?>/b-save.gif" alt="Save" onclick=" document.getElementById('alert').innerHTML=''; selectContacts(); xajax_processFormData(xajax.getFormValues('mainform')); "/></a>
        <!--
          <input type="image" src="<?=$relBasePath?>/public/img/<?=$cwLanguage?>/b-cancel.gif" alt="Cancel" onclick="location.href='../'; return false;"/>
          <input type="image" src="<?=$relBasePath?>/public/img/<?=$cwLanguage?>/b-save.gif" alt="Save" onclick="return checkParam(document.getElementById('client[extension]').value, document.getElementById('client[alias]').value, document.getElementById('client[password]').value, document.getElementById('client[confirm]').value);"/>
        -->
        </div>
      </form>
    </div>
    <script>
      function addAll(){
      	fromSelect=document.getElementById('c_select');
        for(var i=0; i<fromSelect.length; i++){
        	optObj=fromSelect.options[i];
        	if(optObj.disabled==false) optObj.selected=true;
        }
        add();
      }
      function add(){
      	var skip=false;
        var num=0;
      	fromSelect=document.getElementById('c_select');
        toSelect=document.getElementById('g_select');
        for(var i=0; i<fromSelect.length; i++){
        	num=parseInt(document.getElementById('c_num_value').value)+1;
          if(num>100){
          	alert('Directory can contains 100 contacts at most');
            return;
          }
        	optObj=fromSelect.options[i];
          if((optObj.selected==true)&&(optObj.disabled==false)){
          	//check if option already exists
          	skip=false;
            for(var j=0; j<toSelect.length; j++){
        			if(toSelect.options[j].value==optObj.value) skip=true;
            }
            if(skip==true) continue;
            //create new option
          	var newOptObj=document.createElement('option');
            newOptObj.value=optObj.value;
            var optg_id='optg_' + optObj.value.substr(2);
            var text='['+optObj.text+'] '+ document.getElementById(optg_id).label;
            if(text.length>25) text=text.substr(0,25) + '...';
            newOptObj.text=text;
            //add new option
            try {
      				toSelect.add(newOptObj,null); // standards compliant; doesn't work in IE
            }
            catch(ex) {
              toSelect.add(newOptObj); // IE only
            }
            //refresh contact count
            document.getElementById('c_num_value').value=num;
            document.getElementById('c_num_visual').innerHTML='('+ num +'/100)';
          }
        }
      }
      function remove(){
      	fromSelect=document.getElementById('g_select');
        var redo=true;
        while(redo){
          redo=false;
          for(var i=0; i<fromSelect.length; i++){
          	optObj=fromSelect.options[i];
            if(optObj.selected==true){
            	fromSelect.remove(i);
              //refresh contact count
            	num=parseInt(document.getElementById('c_num_value').value)-1;
            	document.getElementById('c_num_value').value=num;
            	document.getElementById('c_num_visual').innerHTML='('+ num +'/100)';
              redo=true;
              break;
            }
          }
        }
      }
      function selectContacts(){
      	fromSelect=document.getElementById('g_select');
        for(var i=0; i<fromSelect.length; i++){
        	fromSelect.options[i].selected=true;
        }
      }
    </script>
  <?
  $contents=ob_get_contents();
  ob_end_clean();
  //================ SIDEBAR ================
  ob_start();
  ?>
    <div class="Sidebar">
      <?$sel="provisioning";include("../../../sidebar.php");?>
      <h1><?=T_("Informations")?></h1>
    </div>
  <?
  $sidebar=ob_get_contents();
  ob_end_clean();
  //================ SETTINGS ================
  $smarty->assign("section", "extensions");
  $smarty->assign("subsection", "");
  $smarty->assign("templateType", "TwoColLeft");  //OneCol, TwoColLeft, TwoColRight
  $smarty->assign("contents", $contents);
  $smarty->assign("sidebar", $sidebar);
  $smarty->display('settings.tpl');
?>

